package com.ufcg.lvc.client.prototipacao;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DateLabel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.ufcg.lvc.client.GreetingServiceCRUD;
import com.ufcg.lvc.client.GreetingServiceCRUDAsync;
import com.ufcg.lvc.client.Teste__;

public class Cadastro {

	AbsolutePanel rootPanel;

	public static GreetingServiceCRUDAsync getServicoCRUD() {
		return GWT.create(GreetingServiceCRUD.class);
	}

	public Cadastro() {

		System.out.println("Tela inicial");
		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		rootPanel = new AbsolutePanel();
		rootPanel.setStyleName("dialogVPanel");
		rootPanel.setSize("1160px", "790px");

		rootPanel.getElement().getStyle().setPosition(Position.RELATIVE);
		AbsolutePanel menuPanel = new AbsolutePanel();
		menuPanel.setStyleName("gwt-panelColorido");
		rootPanel.add(menuPanel, 0, 0);
		menuPanel.setSize("232px", "877px");

		final AbsolutePanel panelRegistro = new AbsolutePanel();
		rootPanel.add(panelRegistro, 238, 64);
		panelRegistro.setSize("905px", "712px");
		
		Label lblNovoCadastro = new Label("Cadastrar");
		lblNovoCadastro.setStyleName("gwt-TituloMedio");
		panelRegistro.add(lblNovoCadastro, 0, 0);
		
		Label lblNewLabel = new Label("Nome completo:");
		panelRegistro.add(lblNewLabel, 60, 69);
		
		Label lblEmail = new Label("E-mail:");
		panelRegistro.add(lblEmail, 60, 111);
		
		Label lblUsurio = new Label("Login:");
		panelRegistro.add(lblUsurio, 60, 151);
		
		Label lblSenha = new Label("Senha:");
		panelRegistro.add(lblSenha, 60, 195);
		
		Label lblConfirmarSenha = new Label("Confirmar senha:");
		panelRegistro.add(lblConfirmarSenha, 60, 239);
		
//		Label lblNmeroDoCato = new Label("Número do cartão:");
//		panelRegistro.add(lblNmeroDoCato, 60, 328);
//		
//		Label lblNomeImpressoNo = new Label("Nome impresso no cartão:");
//		panelRegistro.add(lblNomeImpressoNo, 60, 371);
//		
//		Label lblBandeira = new Label("Bandeira:");
//		panelRegistro.add(lblBandeira, 60, 461);
//		
//		Label lblCdigoDeSegurana = new Label("Código de segurança:");
//		panelRegistro.add(lblCdigoDeSegurana, 60, 414);
//		
//		Label lblVencimento = new Label("Vencimento");
//		panelRegistro.add(lblVencimento, 60, 507);
		
		final TextBox nometb = new TextBox();
		panelRegistro.add(nometb, 264, 69);
		nometb.setSize("358px", "17px");
		
		final TextBox emailtb = new TextBox();
		panelRegistro.add(emailtb, 264, 111);
		emailtb.setSize("358px", "17px");
		
		final TextBox usuariotb = new TextBox();
		panelRegistro.add(usuariotb, 264, 151);
		usuariotb.setSize("213px", "17px");
		
		final PasswordTextBox senhatb = new PasswordTextBox();
		panelRegistro.add(senhatb, 264, 195);
		senhatb.setSize("213px", "17px");
		
		final PasswordTextBox senha2tb = new PasswordTextBox();
		panelRegistro.add(senha2tb, 264, 239);
		senha2tb.setSize("213px", "17px");
		
//		TextBox numeroCartaotb = new TextBox();
//		panelRegistro.add(numeroCartaotb, 264, 328);
//		numeroCartaotb.setSize("213px", "17px");
//		
//		TextBox nomeCartaoTB = new TextBox();
//		panelRegistro.add(nomeCartaoTB, 264, 371);
//		nomeCartaoTB.setSize("213px", "17px");
//		
//		TextBox codSegurancaTB = new TextBox();
//		panelRegistro.add(codSegurancaTB, 264, 414);
//		codSegurancaTB.setSize("213px", "17px");
//				
//		ListBox bandeiraLB = new ListBox();
//		panelRegistro.add(bandeiraLB, 264, 461);
//		bandeiraLB.setSize("223px", "27px");
//		
//		ListBox mesVencimentoLB = new ListBox();
//		panelRegistro.add(mesVencimentoLB, 264, 507);
//		mesVencimentoLB.setSize("128px", "27px");
//		
//		ListBox anoVencimentoLB = new ListBox();
//		panelRegistro.add(anoVencimentoLB, 400, 507);
//		anoVencimentoLB.setSize("87px", "27px");
		
		Button btnFinalizar = new Button("Finalizar");
//		panelRegistro.add(btnFinalizar, 353, 595);
		panelRegistro.add(btnFinalizar, 353, 338);
		btnFinalizar.setSize("91px", "29px");
		btnFinalizar.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if (nometb.getText().trim().equals("") || emailtb.getText().trim().equals("") || usuariotb.getText().trim().equals("") || senhatb.getText().trim().equals("") || senha2tb.getText().trim().equals("")){
					com.google.gwt.user.client.Window.alert("Todos os campos devem ser preenchidos.");		
				}
				else if(nometb.getText().length() < 4){
					com.google.gwt.user.client.Window.alert("O nome deve ter no mínimo 4 caracteres.");
				}
				else if(!isEmailValido(emailtb.getText())){
					com.google.gwt.user.client.Window.alert("Este email não é válido.");
				}
				else if(usuariotb.getText().length() < 4){
					com.google.gwt.user.client.Window.alert("O login deve ter no mínimo 4 caracteres.");
				}
				else if(senhatb.getText().length() < 4){
					com.google.gwt.user.client.Window.alert("A senha deve ter no mínimo 4 caracteres.");
				}
				else if(!senhatb.getText().equals(senha2tb.getText())){
					com.google.gwt.user.client.Window.alert("Senhas não correspondem.");
				}
				else {
					getServicoCRUD().cadastraUsuarioSenha(usuariotb.getText(), senhatb.getText(), nometb.getText(), emailtb.getText(), new AsyncCallback<String>() {
						@Override
						public void onFailure(Throwable caught) {
							com.google.gwt.user.client.Window.alert("Erro na comunicação com o servidor.\nVolte mais tarde");
						}
						@Override
						public void onSuccess(String result) {
							String retorno = result + " ";
							System.out.println(retorno);
							com.google.gwt.user.client.Window.alert(result);
							if (!retorno.startsWith("Erro")) {
								rootPanel.clear();
								final Teste__ i = new Teste__();
								i.onModuleLoad();
							}
						}
					});
				}
			}
		});
		
		Button btnCancelar = new Button("Cancelar");
//		panelRegistro.add(btnNewButton_1, 450, 595);
		panelRegistro.add(btnCancelar, 450, 338);
		btnCancelar.setSize("91px", "29px");
		btnCancelar.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				telaInicial();
			}
		});
		
		Button btnCorrigeFacil = new Button("Corrige Fácil");
		btnCorrigeFacil.setStyleName("gwt-TituloGrande-P-para_Button");
		menuPanel.add(btnCorrigeFacil, 1, 21);
		btnCorrigeFacil.setSize("231px", "61px");

		AbsolutePanel absolutePanel_8 = new AbsolutePanel();
		absolutePanel_8.setStyleName("gwt-Separador");
		rootPanel.add(absolutePanel_8, 238, 45);
		absolutePanel_8.setSize("912px", "3px");

		Label lblBemVindo = new Label("Bem vindo!");
		lblBemVindo.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		rootPanel.add(lblBemVindo, 238, 16);

		DateLabel dateLabel = new DateLabel();
		dateLabel.addAttachHandler(new Handler() {
			public void onAttachOrDetach(AttachEvent event) {
			}
		});
		dateLabel.setWordWrap(false);
		rootPanel.add(dateLabel, 970, 16);
		rootPanel.setVisible(true);

	}

	public AbsolutePanel getPanel() {
		return rootPanel;
	}
	
	private void telaInicial() {
		rootPanel.clear();
		Teste__ i = new Teste__();
		i.onModuleLoad();
	}
	
	public boolean isEmailValido(String email) {
		RegExp p = RegExp.compile("^([a-zA-Z0-9_.\\-+])+@(([a-zA-Z0-9\\-])+\\.)+[a-zA-Z0-9]{2,4}$");						
	    //Pattern p = Pattern.compile("^([a-zA-Z0-9_.\\-+])+@(([a-zA-Z0-9\\-])+\\.)+[a-zA-Z0-9]{2,4}$"); 
		MatchResult m = p.exec(email);
//	    Matcher m = p.matcher(email); 
	    if (m!=null){
	      return true;}
	    else{
	      return false;}
	}
	
}